/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.controller;

import java.util.*;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author 科泰集团教研团队
 * @packageName com.ktjiaoyu
 * @fileName SysRoleController.java
 * @createTime 2024/10/22 09:31:42
 * @lastModify 2024/10/22 09:31:42
 * @version 1.0.0
 */
@Controller
@RequestMapping("/main/role")
public class SysRoleController extends BaseController{
    private static final Logger LOGGER =
            LoggerFactory.getLogger(SysRoleController.class);
    @Autowired
    private SysRoleService sysRoleService;

    @RequestMapping("/list")
    public String list(Model model){
        List<SysRole> list = null;
        try {
            list = sysRoleService.findAll();
            model.addAttribute("list", list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "role/list";
    }

    @GetMapping("/view")
    public String view(Long id, Model model){
        SysRole info = null;
        try {
            info = sysRoleService.findById(id);
            model.addAttribute("item", info);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "role/view";
    }

    @GetMapping("/save")
    public String toSave(Model model){
        model.addAttribute("role", new SysRole());
        return "role/save";
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model){
        SysRole sysRole = null;
        try {
            sysRole = sysRoleService.findById(id);
            model.addAttribute("sysRole", sysRole);
        } catch (Exception e) {
            LOGGER.error("SysRoleController中的toEdit方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    @PostMapping("/save")
    public String doSave(SysRole sysRole){
        try {
            // 通过父类的session方法获取登录用户，由于泛型自动转换无需强转
            SysUser loginUser = session(Constants.SESSION_USER);
            if(sysRole.getId() == null){
                // 如果是添加用户，关联创建用户为当前登陆用户
                sysRole.setCreatedUserId(loginUser.getId());
                sysRole.setCreatedTime(new Date());
            }else{
                // 如果是修改用户，关联修改用户为当前登陆用户
                sysRole.setUpdatedUserId(loginUser.getId());
                sysRole.setUpdatedTime(new Date());
            }
            // 新增和修改公用同一个业务方法
            boolean ok = sysRoleService.saveOrUpdate(sysRole);
            if(ok){
                // 保存成功，跳回列表页面
                return redirect("/main/role/list");
            }
        } catch (Exception e) {
            LOGGER.error("SysRoleController中的doSave方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Map del(@PathVariable("id") Long id){
        Map map = new HashMap();
        boolean ok;
        try {
            if(sysRoleService.countRoleUsers(id) > 0){
                map.put("code", 501);
            }else{
                SysUser loginUser = session(Constants.SESSION_USER);
                ok = sysRoleService.remove(id);
                if(ok){
                    map.put("code", 200);
                }else{
                    map.put("code", 500);
                }
            }

        } catch (Exception e) {
            LOGGER.error("SysRoleController中的del方法执行发生错误。", e);
            map.put("code", 500);
        }
        return map;
    }

    @ResponseBody
    @GetMapping("/codeExist")
    public String codeExist(@RequestParam String code){
        LOGGER.debug("检查用户名code={}的用户是否存在", code);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if(StringUtils.isEmpty(code)){
            resultMap.put("exist", 0);
        }else{
            try {
                SysRole sysRole = sysRoleService.findByCode(code);
                if(null != sysRole) {
                    // 已经存在，设置为1
                    resultMap.put("exist", 1);
                }else {
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                LOGGER.error("SysRoleController中的" +
                        "codeExists方法执行发生错误。", e);
                resultMap.put("error", "出现异常，请联系管理员处理！");
            }
        }
        return JSON.toJSONString(resultMap);
    }
}
